/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useMemo, useState, useRef, useImperativeHandle } from 'react';
import { Descriptions, Spin } from 'antd';
import type { DescriptionsProps } from 'antd';
import { debounce } from 'lodash';

export interface KbDescriptionsColumns {
  label?: string;
  dataIndex: string;
  render?: (value: any, record: any) => React.ReactNode;
}
interface KbDescriptionsProps extends DescriptionsProps {
  request: (params: any) => Promise<any>;
  columns: KbDescriptionsColumns[];
  loading?: boolean;
  params?: any;
  debounceTime?: number;
  actionRef?: any;
}
const KbDescriptions = (props: KbDescriptionsProps) => {
  const {
    request,
    params,
    loading: _loading,
    columns,
    debounceTime = 300,
    actionRef: propsActionRef,
    ...rest
  } = props;
  const actionRef = useRef<any>({});
  useImperativeHandle(propsActionRef, function () {
    return actionRef.current;
  });
  if (propsActionRef) {
    // @ts-ignore
    propsActionRef.current = actionRef.current;
  }

  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<any>(null);

  const getDataSource = debounce(() => {
    if (!request) return;
    if (_loading) {
      setLoading(true);
    }
    request(params).then(({ data }) => {
      setLoading(false);
      setDataSource(data);
    });
  }, debounceTime);

  actionRef.current = {
    reload: () => getDataSource(),
  };
  useMemo(() => {
    getDataSource();
  }, []);
  return (
    <Spin spinning={loading}>
      {dataSource && (
        <Descriptions {...rest}>
          {columns.map((item) =>
            item.render ? (
              item.render(dataSource[item.dataIndex], dataSource)
            ) : (
              <Descriptions.Item label={item.label}>{dataSource[item.dataIndex]}</Descriptions.Item>
            ),
          )}
        </Descriptions>
      )}
    </Spin>
  );
};

export default KbDescriptions;
